/*
 * Copyright (c) 2008-2013 Haulmont. All rights reserved.
 * Use is subject to license terms, see http://www.cuba-platform.com/license for details.
 */

package com.haulmont.asu.web.ui.commission_protocol;

import com.haulmont.asu.entity.CommissionProtocol;
import com.haulmont.asu.entity.DiplomaStudent;
import com.haulmont.asu.entity.Speciality;
import com.haulmont.asu.entity.StudentGroup;
import com.haulmont.cuba.gui.components.AbstractEditor;
import com.haulmont.cuba.gui.components.DateField;
import com.haulmont.cuba.gui.components.LookupField;
import com.haulmont.cuba.gui.data.CollectionDatasource;
import com.haulmont.cuba.gui.data.DataSupplier;
import com.haulmont.cuba.gui.data.Datasource;
import com.haulmont.cuba.gui.data.impl.DsListenerAdapter;

import javax.annotation.Nullable;
import javax.inject.Inject;
import java.util.Map;
import java.util.UUID;

/**
 * Author: Sergey42
 * Date: 30.11.13 21:25
 */
public class CommissionProtocolEditor extends AbstractEditor<CommissionProtocol> {

    @Inject
    protected DataSupplier dataSupplier;

    @Inject
    protected Datasource<CommissionProtocol> protocolDs;
    @Inject
    protected CollectionDatasource<DiplomaStudent, UUID> diplomaStudentDs;
    @Inject
    protected LookupField themeLF;
    @Inject
    protected LookupField specialityLF;
    @Inject
    protected LookupField diplomaLeaderLF;
    @Inject
    protected DateField defenseDateDF;

    @Override
    public void init(Map<String, Object> params) {
        diplomaStudentDs.addListener(new DsListenerAdapter<DiplomaStudent>() {
            @Override
            public void itemChanged(Datasource<DiplomaStudent> ds, @Nullable DiplomaStudent prevItem, @Nullable DiplomaStudent item) {
                enable(true);
                if (item != null) {
                    if (item.getDiplomaProject() != null) {
                        getItem().setProjectTheme(item.getDiplomaProject().getProjectTheme());
                    }
                    getItem().setSpeciality(getSpeciality(item));

                    getItem().setDiplomaLeader(item.getDiplomaProject() != null ? item.getDiplomaProject().getDiplomaLeader() : null);

                } else {
                    getItem().setProjectTheme(null);
                    getItem().setSpeciality(null);
                    getItem().setDiplomaLeader(null);
                }
                enable(false);
            }
        });
    }

    protected Speciality getSpeciality(DiplomaStudent item) {
        StudentGroup studentGroup = item.getStudent().getStudentGroup();
        studentGroup = dataSupplier.reload(studentGroup, "browse");
        return studentGroup.getSpeciality();
    }

    private void enable(boolean b) {
        specialityLF.setEditable(b);
        themeLF.setEditable(b);
        diplomaLeaderLF.setEditable(b);
    }
}
